<?php
/**
 * 
 * 操作会员
 * 
 * @category System
 * @author Steve Liu
 * @copyright Eshifang 
 */

class Web_Model_Member
{
	/**
	 * 默认数据库名
	 * 
	 * @var string
	 */
    static private $_table = 'member';
    
    /**
     * 判断是否已经登录
     * 
     * @return bool
     */
    public static function isSignIn()
    {
        if(!Eren_Registry::get('SESSION')->get('memberID', ''))
        {
            return FALSE;
        } 
        return TRUE;
    }
    
    /**
     * 初始化登录态
     * 
     * @param int $memberID
     * @param string $memberEmail
     * @param string $memberNickName
     * @param int $memberType
     */
    private static function _initSignIn($memberID, $memberEmail, $memberNickName, $memberType)
    {
        Eren_Registry::get('SESSION')->set('memberID', $memberID);
        Eren_Registry::get('SESSION')->set('memberEmail', $memberEmail);
        Eren_Registry::get('SESSION')->set('memberNickName', $memberNickName);
        Eren_Registry::get('SESSION')->set('memberType', $memberType);
        return TRUE;
    }
    
    /**
     * 获得会员ID
     * 
     * @return int
     */
    public static function getID()
    {
        return Eren_Registry::get('SESSION')->get('memberID', '');
    }
    
    /**
     * 获得会员邮箱
     * 
     * @return string
     */
    public static function getEmail()
    {
        return Eren_Registry::get('SESSION')->get('memberEmail', '');
    }
    
    /**
     * 获得会员昵称
     * 
     * @return string
     */
    public static function getNickName()
    {
        return Eren_Registry::get('SESSION')->get('memberNickName', '');
    }
    
    /**
     * 获得会员类型
     * 
     * @return int
     */
    public static function getType()
    {
        return Eren_Registry::get('SESSION')->get('memberType', '');
    }
    
    /**
     * 判断是否是会员
     * 
     * @return bool
     */
    public static function isMember()
    {
        if(self::getType() == 1 || self::getType() == 2)
        {
            return TRUE;
        }
        return FALSE;
    }
    
    /**
     * 判断是否是管理员
     * 
     * @return bool
     */
    public static function isAdmin()
    {
        if(self::getType() == 2)
        {
            return TRUE;
        }
        return FALSE;
    }
    
    /**
     * 登录
     * 
     * @param string $email
     * @param string $password
     * @param bool $ifAuto
     * @throws Eren_Exception
     */
    public static function signIn($email, $password, $ifAuto = FALSE)
    {
        if(!$ifAuto && !Web_Model_Validator::email($email)){
            throw new Eren_Exception('邮箱不合法，请填写正确的邮箱', -1);
        }else if(!$ifAuto && !Web_Model_Validator::password($password)){
            throw new Eren_Exception('密码不合法，请重新填写', -2);
        }
        if(!$ifAuto) $password = Web_Model_Common::MD5Hash($password);
        $ret = self::doSignIn($email, $password);
        if($ret['count'] <= 0){
            if(!$ifAuto){
                throw new Eren_Exception('邮箱或密码错误，请确认后重新输入', -3);
            } else {
            	self::signOut();
            }
        }else {
            self::_initSignIn($ret['data'][0]['member_id'], $email, $ret['data'][0]['member_nickname'], $ret['data'][0]['member_type']);
            self::_updateState($ret['data'][0]['member_id'], $ret['data'][0]['member_count']);
            self::_setAutoSignIn($email, $password);
        }
        return true;
    }
    
    /**
     * 执行登录
     * 
     * @param string $email
     * @param string $password
     */
    public static function doSignIn($email, $password)
    {
        $DB  = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->where('member_email', '=', $email)
                  ->wAND()
                  ->where('member_password', '=', $password)
                  ->select();
        return $ret;
    }
    
    /**
     * 更新最后登录时间
     * 
     * @param string $email
     */
    private static function _updateState($memberID, $memberCount)
    {
        $now = Web_Model_Common::getNowTime();
        $DB  = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->where('member_id', '=', $memberID)
                  ->update(array('member_last_time'=>$now, 
                                 'member_count'=>$memberCount+1));
        return TRUE;
    }
    
    /**
     * 设置自动登录
     * 
     * @param string $email
     * @param string $password
     */
    private static function _setAutoSignIn($email, $password)
    {
        Eren_Cookie::set('memberEmail', $email);
        Eren_Cookie::set('memberPassword', $password);
    }
    
    /**
     * 执行自动登录
     */
    public static function autoSignIn()
    {
        if(self::isSignIn()) return;
        $email       = Eren_Cookie::get('memberEmail', '');
        $password    = Eren_Cookie::get('memberPassword', '');
        if($email && $password){
             self::signIn($email, $password, TRUE);
        }
    }
    
    /**
     * 退出
     */
    public static function signOut()
    {
        Eren_Registry::get('SESSION')->delete('memberID');
        Eren_Registry::get('SESSION')->delete('memberEmail');
        Eren_Registry::get('SESSION')->delete('memberNickName');
        Eren_Registry::get('SESSION')->delete('memberType');
        Eren_Cookie::delete('memberEmail');
        Eren_Cookie::delete('memberPassword');
    }
    
    /**
     * 获得所有会员
     * 
     * @param int $start
     * @param int $limit
     * @return array
     */
    public static function getAll($start=0, $limit=1000)
    {
        $DB  = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->orderBy('member_id', 'DESC')
                  ->limit($start, $limit)
                  ->select();
        $ret['total'] = self::getCount();
        return $ret;
    }
    
    /**
     * 获得会员数量
     * 
     * @return int
     */
    public static function getCount()
    {
        $DB  = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->count();
        return $ret;
    }
    
    /**
     * 判断Email是否已经存在
     * 
     * @param string $email
     * @return bool
     */
    public static function ifEmailExist($email)
    {
        $DB = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->where('member_email', '=', $email)
                  ->count();
                  
        if($ret > 0){
            return TRUE;
        }else{
            return FALSE;
        }
    }
    
    /**
     * 判断Nickname是否已经存在
     * 
     * @param string $email
     * @return bool
     */
    public static function ifNickNameExist($nickName)
    {
        $DB = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->where('member_nickname', '=', $nickName)
                  ->count();
                  
        if($ret > 0){
            return TRUE;
        }else{
            return FALSE;
        }
    }
    
    /**
     * 注册新会员
     * 
     * @param string $email
     * @param string $nickname
     * @param string $password
     * @param string $repassword
     * @throws Eren_Exception
     * @return int
     */
    public static function signUp($email, $nickname, $password, $repassword)
    {
        $email    = Eren_Filter::htmlspecialchars(trim($email));
        $nickname = Eren_Filter::htmlspecialchars(trim($nickname));
        if(!Web_Model_Validator::email($email)){
            throw new Eren_Exception('邮箱不合法，请填写正确的邮箱', -1);
        }
        if(self::ifEmailExist($email)){
            throw new Eren_Exception('邮箱已经存在，请更换后重试', -1);
        }
        if(!Web_Model_Validator::nickName($nickname)){
            throw new Eren_Exception('昵称不合法，请填写正确的昵称', -2);
        }
        if(self::ifNickNameExist($nickname)){
            throw new Eren_Exception('昵称已经存在，请更换后重试', -2);
        }
        if(!Web_Model_Validator::password($password)){
            throw new Eren_Exception('密码不合法，请重新填写', -3);
        }
        if(!Web_Model_Validator::password($repassword)){
            throw new Eren_Exception('确认密码不合法，请重新填写', -4);
        }
        if($password !== $repassword){
            throw new Eren_Exception('确认密码和密码不一致，请重新填写', -5);
        }
        $fields = array(
        'member_email'       => $email,
        'member_password'    => Web_Model_Common::MD5Hash($password),
        'member_nickname'    => $nickname,
        'member_signup_time' => Web_Model_Common::getNowTime(),
        'member_last_time'   => Web_Model_Common::getNowTime()
        );
        $DB = Eren_Registry::get('DB');
        $id = $DB->table(self::$_table)
                 ->insert($fields);
        self::signIn($email, $password);
        return $id;
    }
    
    /**
     * 设置会员级别
     * 
     * @param int $memberID
     * @param int $memberType
     * @throws Eren_Exception
     */
    public static function setType($memberID, $memberType)
    {
        $memberID = intval($memberID);
        $memberType = intval($memberType);
        if($memberType<0 || $memberType >2){
            throw new Eren_Exception('级别异常', -1);
        }
        $DB  = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->where('member_id', '=', $memberID)
                  ->update(array('member_type'=>$memberType));
        return TRUE;
    }
}